import Vue from 'vue'
import VueRouter from 'vue-router'
import UserLogin from '@/views/UserLogin'
import LayoutHome from '@/views/LayoutHome'
import HomePage from '@/views/HomePage'
import LookingRoom from '@/views/LookingRoom'
import DataMessage from '@/views/DataMessage'
import UserMy from '@/views/UserMy'
import MyCollection from '@/views/MyViews/MyCollection'
import MyRent from '@/views/MyViews/MyRent'
import PushHouse from '@/views/HomeViews/PushHouse'
import CityList from '@/views/HomeViews/CityList'
import MapHouse from '@/views/HomeViews/MapHouse'
import SearchCommunity from '@/views/HomeViews/SearchCommunity'
import { getToken } from '@/utils/storage'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: UserLogin
  },
  {
    path: '/collection',
    component: MyCollection
  },
  {
    path: '/rent',
    component: MyRent
  },
  {
    path: '/pushhouse',
    component: PushHouse
  },
  {
    path: '/citylist',
    component: CityList
  },
  {
    path: '/maphouse',
    component: MapHouse
  },
  {
    path: '/searchcommunity',
    component: SearchCommunity
  },
  {
    path: '/',
    component: LayoutHome,
    redirect: '/my',
    children: [
      {
        path: '/home',
        component: HomePage
      },
      {
        path: '/room',
        component: LookingRoom
      },
      {
        path: '/data',
        component: DataMessage
      },
      {
        path: '/my',
        component: UserMy
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

const whiteList = ['/login'] // 白名单列表，记录无需权限访问的所有页面

router.beforeEach((to, from, next) => {
  const token = getToken()
  // 如果有token，直接放行
  if (token) {
    next()
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      // (2) 否则拦截到登录
      next('/login')
    }
  }
})

export default router
